<template>
  <div class="result-editor-container">
    <n-card class="editor-card">
      <template #header>
        <div class="card-header">
          <h1>AI结果编辑器</h1>
          <div class="header-actions">
            <n-button @click="saveChanges" type="primary">
              <template #icon>
                <n-icon>
                  <SaveOutline />
                </n-icon>
              </template>
              保存更改
            </n-button>
            <n-button @click="applyToProject">
              <template #icon>
                <n-icon>
                  <CheckmarkDoneOutline />
                </n-icon>
              </template>
              应用到项目
            </n-button>
            <n-button @click="goBack">
              <template #icon>
                <n-icon>
                  <ArrowBackOutline />
                </n-icon>
              </template>
              返回
            </n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="editor-section">
          <h3>内容编辑</h3>
          <n-input
            v-model:value="editorContent"
            type="textarea"
            placeholder="编辑AI生成的内容..."
            :autosize="{ minRows: 20, maxRows: 30 }"
          />
          
          <div class="editor-tools">
            <n-space>
              <n-button-group size="small">
                <n-button @click="formatText">格式化</n-button>
                <n-button @click="checkGrammar">语法检查</n-button>
                <n-button @click="improveText">优化内容</n-button>
              </n-button-group>
              
              <n-button size="small" @click="revertToOriginal">
                <template #icon>
                  <n-icon>
                    <RefreshOutline />
                  </n-icon>
                </template>
                还原原始内容
              </n-button>
            </n-space>
          </div>
        </div>
        
        <div class="tools-section">
          <n-tabs type="line" animated>
            <n-tab-pane name="suggestions" tab="智能建议">
              <div class="tab-content">
                <n-alert title="内容分析" type="info" v-if="contentAnalysis">
                  {{ contentAnalysis }}
                </n-alert>
                
                <div class="suggestions-list" v-if="suggestions.length > 0">
                  <h4>改进建议</h4>
                  <n-list hoverable>
                    <n-list-item v-for="(suggestion, index) in suggestions" :key="index">
                      <n-thing :title="suggestion.title" :description="suggestion.description">
                        <template #footer>
                          <n-button size="small" @click="applySuggestion(index)">应用</n-button>
                        </template>
                      </n-thing>
                    </n-list-item>
                  </n-list>
                </div>
                
                <n-empty description="暂无建议" v-else>
                  <template #extra>
                    <n-button size="small" @click="analyzeContent">分析内容</n-button>
                  </template>
                </n-empty>
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="revisions" tab="修订历史">
              <div class="tab-content">
                <div class="revisions-list" v-if="revisions.length > 0">
                  <n-timeline>
                    <n-timeline-item
                      v-for="(revision, index) in revisions"
                      :key="index"
                      :type="getRevisionType(index)"
                      :title="formatRevisionTime(revision.timestamp)"
                    >
                      <div class="revision-content">
                        {{ revision.summary }}
                        <div class="revision-actions">
                          <n-button size="tiny" @click="loadRevision(index)">恢复此版本</n-button>
                        </div>
                      </div>
                    </n-timeline-item>
                  </n-timeline>
                </div>
                
                <n-empty description="暂无修订历史" v-else />
              </div>
            </n-tab-pane>
            
            <n-tab-pane name="variations" tab="内容变体">
              <div class="tab-content">
                <div class="generate-variations">
                  <n-button @click="generateVariations" :loading="generatingVariations">
                    生成内容变体
                  </n-button>
                  <n-text depth="3">基于当前内容生成多个不同风格的变体</n-text>
                </div>
                
                <div class="variations-list" v-if="variations.length > 0">
                  <n-divider />
                  
                  <div
                    v-for="(variation, index) in variations"
                    :key="index"
                    class="variation-item"
                  >
                    <div class="variation-header">
                      <h4>变体 {{ index + 1 }} - {{ variation.style }}</h4>
                      <n-button size="small" @click="applyVariation(index)">应用此变体</n-button>
                    </div>
                    <div class="variation-content">
                      <n-scrollbar style="max-height: 200px;">
                        {{ variation.content }}
                      </n-scrollbar>
                    </div>
                  </div>
                </div>
              </div>
            </n-tab-pane>
          </n-tabs>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NButtonGroup,
  NIcon,
  NSpace,
  NInput,
  NTabs,
  NTabPane,
  NList,
  NListItem,
  NThing,
  NEmpty,
  NAlert,
  NTimeline,
  NTimelineItem,
  NDivider,
  NScrollbar,
  NText
} from 'naive-ui'
import {
  SaveOutline,
  ArrowBackOutline,
  CheckmarkDoneOutline,
  RefreshOutline
} from '@vicons/ionicons5'

const router = useRouter()
const message = useMessage()

// 编辑器内容
const editorContent = ref('')
const originalContent = ref('')

// 内容分析
const contentAnalysis = ref('')

// 智能建议
const suggestions = ref([
  {
    title: '使描述更具体',
    description: '考虑添加更多感官细节，如颜色、声音或质地，使场景更加生动。',
    action: (text: string) => text // 实际应用中会有更复杂的处理逻辑
  },
  {
    title: '简化长句',
    description: '第二段有一个较长的复合句，可以考虑拆分为两个短句以提高可读性。',
    action: (text: string) => text // 实际应用中会有更复杂的处理逻辑
  }
])

// 修订历史
const revisions = ref([
  {
    content: '原始AI生成内容...',
    summary: 'AI初始生成',
    timestamp: new Date(Date.now() - 3600000)
  },
  {
    content: '经过简单编辑的内容...',
    summary: '优化了角色描述',
    timestamp: new Date(Date.now() - 1800000)
  }
])

// 内容变体
const variations = ref<any[]>([])
const generatingVariations = ref(false)

// 在组件挂载时初始化
onMounted(() => {
  // 从localStorage获取AI生成的内容
  const savedContent = localStorage.getItem('aiGeneratedText')
  if (savedContent) {
    editorContent.value = savedContent
    originalContent.value = savedContent
    
    // 初始化修订历史
    if (revisions.value.length === 0) {
      revisions.value.push({
        content: savedContent,
        summary: 'AI初始生成',
        timestamp: new Date()
      })
    }
  }
})

// 保存更改
const saveChanges = () => {
  if (!editorContent.value.trim()) {
    message.warning('内容不能为空')
    return
  }
  
  // 添加到修订历史
  revisions.value.unshift({
    content: editorContent.value,
    summary: '手动编辑保存',
    timestamp: new Date()
  })
  
  message.success('更改已保存')
  // 在实际项目中，这里会将内容保存到项目数据中
}

// 应用到项目
const applyToProject = () => {
  if (!editorContent.value.trim()) {
    message.warning('内容不能为空')
    return
  }
  
  message.success('内容已应用到当前项目')
  // 在实际项目中，这里会有将内容应用到项目的逻辑
  
  // 导航回项目页面
  router.push('/workspace/editor')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化文本
const formatText = () => {
  if (!editorContent.value.trim()) return
  
  // 简单的格式化示例，实际应用中会有更复杂的格式化逻辑
  const formattedText = editorContent.value
    .replace(/\n{3,}/g, '\n\n') // 减少多余的空行
    .replace(/\s+/g, ' ') // 减少多余的空格
    .replace(/\n /g, '\n') // 删除行首空格
  
  editorContent.value = formattedText
  message.success('文本已格式化')
}

// 检查语法
const checkGrammar = () => {
  if (!editorContent.value.trim()) return
  
  // 模拟语法检查过程
  setTimeout(() => {
    message.success('语法检查完成')
    // 这里应该有实际的语法检查逻辑和结果展示
  }, 1000)
}

// 优化内容
const improveText = () => {
  if (!editorContent.value.trim()) return
  
  // 模拟内容优化过程
  setTimeout(() => {
    // 这里应该有实际的内容优化逻辑
    message.success('内容已优化')
  }, 1500)
}

// 还原原始内容
const revertToOriginal = () => {
  if (!originalContent.value) return
  
  editorContent.value = originalContent.value
  message.info('已还原到原始内容')
}

// 分析内容
const analyzeContent = () => {
  if (!editorContent.value.trim()) {
    message.warning('请先输入内容')
    return
  }
  
  // 模拟内容分析过程
  setTimeout(() => {
    contentAnalysis.value = '当前内容约包含 ' + countWords(editorContent.value) + ' 个词。文本风格偏描述性，可以考虑增加一些对话或情感描写来增强表现力。'
    
    // 根据内容生成建议
    suggestions.value = [
      {
        title: '增加对话元素',
        description: '考虑添加一些角色对话，使内容更加生动。',
        action: (text: string) => text // 实际应用中会有更复杂的处理逻辑
      },
      {
        title: '强化情感描写',
        description: '可以增加更多角色内心活动的描写，使读者更能感受到情感变化。',
        action: (text: string) => text // 实际应用中会有更复杂的处理逻辑
      }
    ]
    
    message.success('内容分析完成')
  }, 1000)
}

// 应用建议
const applySuggestion = (index: number) => {
  const suggestion = suggestions.value[index]
  if (!suggestion) return
  
  // 在实际应用中，这里会有更复杂的逻辑来应用建议
  editorContent.value = suggestion.action(editorContent.value)
  
  message.success(`已应用建议: ${suggestion.title}`)
  
  // 添加到修订历史
  revisions.value.unshift({
    content: editorContent.value,
    summary: `应用建议: ${suggestion.title}`,
    timestamp: new Date()
  })
}

// 加载修订版本
const loadRevision = (index: number) => {
  const revision = revisions.value[index]
  if (!revision) return
  
  editorContent.value = revision.content
  message.info(`已恢复到版本: ${formatRevisionTime(revision.timestamp)}`)
}

// 生成内容变体
const generateVariations = () => {
  if (!editorContent.value.trim()) {
    message.warning('请先输入内容')
    return
  }
  
  generatingVariations.value = true
  
  // 模拟生成变体的过程
  setTimeout(() => {
    variations.value = [
      {
        style: '简洁风格',
        content: truncateText(editorContent.value, 0.7) // 简单示例：截取原文的70%
      },
      {
        style: '详细风格',
        content: editorContent.value + '\n\n' + '这是附加的详细描述内容，用于丰富原始文本，增加更多的细节和背景信息。在实际应用中，这将是由AI生成的与原始内容相关的扩展文本。'
      },
      {
        style: '戏剧风格',
        content: editorContent.value.replace(/\./g, '!') // 简单示例：将句号替换为感叹号
      }
    ]
    
    generatingVariations.value = false
    message.success('已生成3个内容变体')
  }, 2000)
}

// 应用变体
const applyVariation = (index: number) => {
  const variation = variations.value[index]
  if (!variation) return
  
  editorContent.value = variation.content
  message.success(`已应用变体: ${variation.style}`)
  
  // 添加到修订历史
  revisions.value.unshift({
    content: variation.content,
    summary: `应用变体: ${variation.style}`,
    timestamp: new Date()
  })
}

// 获取修订类型（用于时间线样式）
const getRevisionType = (index: number) => {
  const types = ['success', 'info', 'warning', 'error']
  return types[index % types.length]
}

// 格式化修订时间
const formatRevisionTime = (date: Date) => {
  return date.toLocaleString('zh-CN', {
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
  })
}

// 统计词数（简化版）
const countWords = (text: string) => {
  return text.split(/\s+/).filter(word => word.length > 0).length
}

// 截取文本（用于生成简洁变体）
const truncateText = (text: string, ratio: number) => {
  const sentences = text.split(/[.!?。！？]+/).filter(s => s.trim().length > 0)
  const truncatedLength = Math.max(1, Math.floor(sentences.length * ratio))
  return sentences.slice(0, truncatedLength).join('. ') + '.'
}
</script>

<style lang="scss" scoped>
.result-editor-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .editor-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .header-actions {
        display: flex;
        gap: 12px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 3fr 2fr;
    gap: 24px;
    margin-top: 20px;
    
    @media (max-width: 1200px) {
      grid-template-columns: 1fr;
    }
  }
  
  .editor-section {
    h3 {
      margin-top: 0;
      margin-bottom: 16px;
    }
    
    .editor-tools {
      margin-top: 16px;
    }
  }
  
  .tools-section {
    .tab-content {
      padding: 16px 0;
    }
    
    .suggestions-list {
      margin-top: 16px;
      
      h4 {
        margin-top: 0;
        margin-bottom: 12px;
      }
    }
    
    .revision-content {
      font-size: 14px;
      
      .revision-actions {
        margin-top: 8px;
      }
    }
    
    .generate-variations {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }
    
    .variation-item {
      margin-bottom: 20px;
      
      .variation-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        
        h4 {
          margin: 0;
        }
      }
      
      .variation-content {
        padding: 12px;
        border: 1px solid var(--border-color);
        border-radius: 4px;
        background-color: var(--body-color);
        font-size: 14px;
      }
    }
  }
}
</style> 